﻿namespace My.Hydrator.Conventions
{
    using System;
    using System.ComponentModel.Composition;
    using My.Hydrator.Helpers;

    [Export(typeof(ITypeConvention))]
    public class DecimalTypeConvention : BaseTypeConvention, ITypeConvention
    {
        private readonly decimal minValue;

        private readonly decimal maxValue;

        public DecimalTypeConvention()
            : this(0, decimal.MaxValue)
        {
        }

        public DecimalTypeConvention(decimal minValue, decimal maxValue)
        {
            this.minValue = minValue;
            this.maxValue = maxValue;
        }

        public Type Type
        {
            get { return typeof(decimal); }
        }

        public object GenerateValue(object[] customAttributes)
        {
            this.GetAttributes(customAttributes);

            decimal result;

            if (this.IsDataTypeAttributePresent)
            {
                var formatter = this.GetFormatter(this.DataTypeAttribute);
                if (formatter != null)
                {
                    return formatter.GetFormat();
                }
            }

            if (this.IsRangeAttributePresent)
            {
                var min = Convert.ToDecimal(this.RangeAttribute.Minimum.ToString());
                var max = Convert.ToDecimal(this.RangeAttribute.Maximum.ToString());

                result = this.Random.NextDecimal(min, max);
            }
            else
            {
                result = this.Random.NextDecimal(this.minValue, this.maxValue);
            }

            return result;
        }
    }
}
